/*
    客户端
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <arpa/inet.h>

int main(int argc, char* argv[])
{
    // ./01_c <filename>
    if(argc != 2)
    {
        perror("参数错误\n");
        exit(1);
    }
    // 1.创建套接字
    int client_fd = socket(AF_INET, SOCK_STREAM, 0);

    // 2.connect 连接 
    struct sockaddr_in client_addr;
    memset(&client_addr, 0, sizeof(client_addr));
    client_addr.sin_family = AF_INET;
    client_addr.sin_port = htons(8888);
    inet_pton(AF_INET, "121.37.15.117", &client_addr.sin_addr.s_addr);

    int ret = connect(client_fd, (struct sockaddr*)&client_addr, sizeof(client_addr));
    if(ret == -1)
    {
        perror("连接失败！");
        exit(1);
    }
    // 3.发送请求
    char buf[1024];
    memset(buf, 0, sizeof(buf));
    
    // 先发送文件名称
        // 发送文件名长度
    int name_len = strlen(argv[1]);
    write(client_fd, &name_len, sizeof(name_len));
    // 发送文件名
    write(client_fd, argv[1], name_len);

    FILE* fp =fopen(argv[1], "r");
    if(fp == NULL)
    {
        perror("文件打开失败！");
        exit(1);
    }
    int size = 0;
    while((size = fread(buf, 1, sizeof(buf), fp)) > 0)
    {
        write(client_fd, buf, size);
        printf("send %d\n", size);
        memset(buf, 0, sizeof(buf));
    }
    fclose(fp);
    // 5.关闭套接字
    close(client_fd);
    printf("文件发送完成！\n");
    return 0;
}